var v_functionContent = v_functionContent;
Ext.onReady(function() {

    Ext.create('Ext.Viewport', {
        layout: 'fit',
        items: [{
            id: 'main_panel',
            layout: 'border',
            items: [getContentPanel(), getMsgPanel()]
        }]
    });
    initAll();
    setTableOptionsObject();
});

function getTableColumnUrl() {
    return getRoot() + '/websql/autoCompleteTableColumns?dataId=' + dataBase_id + '&baseType=' + base_type + '&dataSourceId=' + dataSource_id + '&dataSource=' + data_source + '&isLocal=' + isLocal;
}

function getParamType() {
    return "column_group";
}

function setTableOptionsObject(comboValue) {
    var tmpNowDBName = comboValue ? comboValue: nowDBName;
    ajax({ //发送同步请求
        async: false,
        url: getTableColumnUrl(),
        params: {
            dbName: tmpNowDBName
        },
        success: function(resp) {
            var json = jsonDecode(resp.responseText);
            if (json.success) {
                var databaseData = json.databases;
                CM_NOW_DATABASE = tmpNowDBName;
                var tableData = json.tables;
                var databaseResObj = {};
                var tableResObj = {};
                for (var i = 0; i < databaseData.length; i++) {
                    databaseResObj[databaseData[i].databaseName] = null;
                }
                for (var i = 0; i < tableData.length; i++) {
                    var tmpName = tableData[i].tableName;
                    var tmpComment = tableData[i].tableComment;
                    tableResObj[tmpName] = {
                        "__cm__comment": tmpComment
                    };
                }
                CM_TABLES = tableResObj;
                databaseResObj[CM_NOW_DATABASE] = CM_TABLES;
                CM_DATABASES = databaseResObj;
                Ext.getCmp('sql_content').editor.setOption('hintOptions', {
                    databases: databaseResObj,
                    tables: tableResObj
                });
            }
        }
    });
};

var action_fun = {
    now_parameters: {},
    saveErrorProcess: function(msg) {
        Ext.getCmp('msg_panel').show();
        var errorLineIndex = -1,
        lineIndex = -1;
        if (msg.contains("You have an error in your SQL syntax;") && msg.contains("near")) {
            var index = msg.indexOf("near") + 4;
            var realMsg = msg.substring(index).trim();
            msg = "<b>SQL语法出现错误，位置在以下关键字前后：</b>" + realMsg;
            lineIndex = msg.indexOf("line");
            if (lineIndex != -1) {
                errorLineIndex = parseInt(msg.substring(lineIndex + 4).trim()) - 1;
            }
            if (realMsg.startsWith("')")) {
                if (realMsg.substring(0, 20).toUpperCase().contains("RETURNS")) {
                    msg += "<br/><br/><b>原因分析：</b>通常是入口参数不正确或入口参数的类型不正确导致（例如入口参数类型varchar没有写长度）。";
                }
            }
        } else if (msg.contains("at line")) {
            lineIndex = msg.indexOf("at line");
            if (lineIndex != -1) {
                errorLineIndex = parseInt(msg.substring(lineIndex + 7).trim()) - 1;
            }
        } else if (msg.contains("Incorrect parameter count in the call to native function")) {
            var functionName = msg.substring("Incorrect parameter count in the call to native function".length).trim();
            var realFunctionName = functionName.substring(1, functionName.length - 1);
            msg = "调用函数：[" + functionName + "]传入的参数数量不正确。";
            var contentIndex = content.indexOf(realFunctionName);
            var tmp = content.substring(0, contentIndex);
            errorLineIndex = tmp.length - tmp.replaceAll('\n', "").length;
        }
        document.getElementById("msg_panel_content").innerHTML = "<span style='font-size: 16px;color: red'>函数保存失败：</span><br/>" + msg;
        if (errorLineIndex != -1) {
            var sqlContent = Ext.getCmp('sql_content');
            var lineContent = sqlContent.editor.getLine(errorLineIndex);
            sqlContent.editor.focus(true);
            sqlContent.editor.setCursor(errorLineIndex, lineContent.length);
            var codeMirrors = Ext.select('.CodeMirror-linebackground');
            codeMirrors.each(function(ele) {
                ele.setStyle('background-color', "red");
                ele.setStyle('opacity', '0.45');
            });
        }
    },
    executeFunctionDoing: function(parameters, functionName, dbName) {
        if (action_fun.isExecute) {
            return;
        }
        action_fun.isExecute = true; //正在执行
        parameters = parameters || "";
        var params = {
            name: functionName,
            dbName: dbName || nowDBName,
            parameters: parameters
        };
        action_fun.cleanMsg();
        Ext.getBody().mask('正在执行函数...');
        ajaxLongTime({
            url: '/structure/function/execute-function.do',
            getDataUrl: '/structure/function/get-function-result.do',
            endCode: 'END',
            maxRequestTimeout: 6000,
            params: params,
            success: function(resp) {
                action_fun.isExecute = false;
                Ext.getBody().unmask();
                Ext.getCmp('msg_panel').show();
                var json = jsonDecode(resp.responseText);
                if (json.success) {
                    var result = json.root.result;
                    result = result ? result: "NULL";
                    document.getElementById("msg_panel_content").innerHTML = "<span style='font-size: 16px;color: red;padding-left: 10px;'>函数执行成功。</span><span style='padding-left: 10px;'>耗时：[ " + commons_tools.numberWithCommas(json.root['timeDelay']) + "ms. ]，返回结果：</span><br/><pre style='margin-left: 10px;'>" + result + "</pre>";
                } else {
                    document.getElementById("msg_panel_content").innerHTML = "<span style='font-size: 16px;color: red;padding-left: 10px;'>函数执行失败，失败原因：</span><br/><pre style='margin-left: 10px;'>" + json.root + "</pre>";
                }
            },
            notifyTime: function(time) {
                Ext.getBody().unmask();
                Ext.getBody().mask('函数还在执行中，请不要强制刷新或关闭页面，函数大概已执行：[ ' + commons_tools.numberWithCommas(time) + "ms. ]");
            }
        })
    },
    isExecute: false,
    executeFunction: function() {
        var content = Ext.getCmp('sql_content').getValue();
        if (!content || content.trim().length == 0) {
            return Ext.Msg.alert('提示', '函数的内容不能为空。');
        }

        if (!v_functionContent || v_functionContent != content) {
            action_fun.saveFunction(true, action_fun.executeFunction);
        } else {
            Ext.getBody().mask('正在获取函数参数信息...');
            ajax({
                url: '/structure/function/get-function-config.do',
                params: {
                    script: content
                },
                success: function(resp) {
                    Ext.getBody().unmask();
                    var data = jsonDecode(resp.responseText);
                    if (data.success) {
                        var params = data.root['params'];
                        if (params && params.length > 0) {
                            action_fun.executeFunctionSetParams(params, data.root['name'], data.root['dbName']);
                        } else {
                            action_fun.executeFunctionDoing("", data.root['name'], data.root['dbName']);
                        }
                    } else {
                        $.message.error("函数参数信息获取失败：" + json.root);
                    }
                }
            });
        }
    },
    setParameterWindow: null,
    executeFunctionSetParams: function(params, functionName, dbName) {
        if (action_fun.setParameterWindow) {
            action_fun.setParameterWindow.close();
            action_fun.setParameterWindow = null;
        }
        params.each(function(row) {
            var name = row['name'];
            if (action_fun.now_parameters[name]) {
                row['value'] = action_fun.now_parameters[name];
            }
        });
        var paramStore = new Ext.data.Store({
            fields: ['name', 'type', 'value'],
            data: params,
            proxy: {
                type: 'memory'
            }
        });
        var grid = new Ext.grid.Panel({
            selType: 'rowmodel',
            region: 'center',
            viewConfig: {
                stripeRows: true,
                enableTextSelection: true
            },
            plugins: [new Ext.grid.plugin.CellEditing({
                clicksToEdit: 1
            })],
            columns: [{
                xtype: 'rownumberer'
            },
            {
                text: '参数',
                dataIndex: 'name',
                width: 275,
                sortable: false,
                renderer: function(v, css, row) {
                    return "<span style='font-weight: bold'>" + v + "</span><span style='padding-left: 10px;'> " + row.get('type') + "</span>";
                }
            },
            {
                text: '参数值',
                dataIndex: 'value',
                width: 400,
                sortable: false,
                editor: {
                    xtype: 'textfield'
                }
            }],
            store: paramStore
        });
        var win = action_fun.setParameterWindow = new IDB.Window({
            width: 720,
            height: 300,
            title: '请设置函数的入口参数值',
            layout: 'fit',
            buttonAlign: 'center',
            closable: true,
            items: [grid],
            buttons: [{
                text: '开始执行',
                handler: function() {
                    var parameters = '';
                    action_fun.now_parameters = {};
                    grid.store.each(function(row) {
                        var v = row.get('value');
                        if (v && Ext.util.Format.trim(v).length > 0) {
                            parameters += "'" + v.replaceAll("'", "''") + "',";
                            action_fun.now_parameters[row.get('name')] = v;
                        } else {
                            parameters += "null,";
                        }
                    });
                    parameters = parameters.substring(0, parameters.length - 1);
                    action_fun.executeFunctionDoing(parameters, functionName, dbName);
                    win.close();
                }
            },
            {
                text: '取消',
                handler: function() {
                    win.close();
                }
            }]
        });
    },
    refreshFunctionCallBack: function(name, type, dbName) {
        if (window.onunload) {
            window.onunload = null;
        }
        if (window.onbeforeunload) {
            window.onbeforeunload = null;
            3
        }
        window.parent.refreshFunctionCallBack(tabId, name, type, dbName, panelKey);
    },
    saveFunction: function(force, fn) {
        action_fun.cleanMsg();
        var content = Ext.getCmp('sql_content').getValue();
        if (!content || content.trim().length == 0) {
            action_fun.isExecute = false;
            return Ext.Msg.alert('提示', '函数的内容不能为空。');
        }
        var baseFormInfoValues = {};
        	baseFormInfoValues.func_name = func_name;
        	baseFormInfoValues.auserEmail = func_auserEmail;
        	baseFormInfoValues.projectName = func_projectName;
        	baseFormInfoValues.returnType = func_returnType;
        	baseFormInfoValues.sqlUsage = func_sqlUsage;
        	baseFormInfoValues.comment = func_comment;
	        baseFormInfoValues.script = content;
	        baseFormInfoValues.dbName = nowDBName;
	        baseFormInfoValues.oldFunctionName = v_functionName;
	        baseFormInfoValues.forceExecute = force;
	        baseFormInfoValues.databaseId = dataBase_id;
	        baseFormInfoValues.datasourceId = dataSource_id;
	        baseFormInfoValues.dataSource = data_source;
	        baseFormInfoValues.baseType = now_db_type;
	        baseFormInfoValues.isLocal = isLocal;
		    baseFormInfoValues.sqlType = 'A SQL';
		    baseFormInfoValues.objectType = 'FUNCTION';
        Ext.getBody().mask('正在保存函数...');
        ajax({
            url: getRoot()+'/dataManage/executeScript',
            params: baseFormInfoValues,
            success: function(resp) {
            	Ext.getBody().unmask();
                Ext.getCmp('msg_panel').show();
                var json = jsonDecode(resp.responseText);
                var data = json.root;
                if(json.success) {
                	if(isLocal =='isLocal'){
                		$.message.success(""+data);
                	}else{
                		$.feedbackMessage({type: 'success',message: data,showTime:5000});
                	}
                	window.parent.object_panel.refreshone(window.parent.objectTypeMap.progobjs);
                    setTimeout(function() {
                        action_fun.refreshFunctionCallBack(baseFormInfoValues['name'], "func", nowDBName);
                    },
                    1500);
                }else {
                    action_fun.saveErrorProcess(data);
                }
            }
        });
    },
    linkHelp: function() {
        window.open('https://dev.mysql.com/doc/refman/5.6/en/create-procedure.html');
    },
    cleanMsg: function() {
        document.getElementById("msg_panel_content").innerHTML = "&nbsp;"
    },
    setInfoBefore: function() {
        var content = Ext.getCmp('sql_content').getValue();
        Ext.getBody().mask('正在解析函数的选项信息....');
        ajax({
            url: '/structure/function/get-function-config.do',
            params: {
                script: content
            },
            success: function(resp) {
                Ext.getBody().unmask();
                var json = jsonDecode(resp.responseText);
                if (json.success) {
                    action_fun.setInfo(json.root);
                } else {
                    action_fun.saveErrorProcess(json.root);
                }
            }
        });
    },
    setInfo: function(config) {
        var baseInfoForm = new Ext.Panel({
            region: 'center',
            layout: {
                type: 'vbox',
                align: 'left' //左边对其
            },
            defaults: {
                padding: '10 2 2 2'
            },
            items: [{
                //SQL_SECURITY
                height: 55,
                layout: {
                    type: 'hbox',
                    align: 'top' //向上对其
                },
                items: [{
                    xtype: 'panel',
                    width: 130,
                    html: '<span style="margin-right: 13px;float: right;margin-top: 10px;font-weight: bold">' + '<span style="font-size: 13px;">SQL_SECURITY：</span>' + '</span>'
                },
                {
                    xtype: 'panel',
                    width: 90,
                    html: '<span style="margin-right: 13px;">' + '<input name="v_saveSecurityField" type="button" value="默认" onclick="action_fun.select(this)" class="radio_class_1" style="width: 80px;height: 29px;"/>' + '</span>'
                },
                {
                    xtype: 'panel',
                    width: 90,
                    html: '<span style="margin-right: 13px;">' + '<input name="v_saveSecurityField" type="button" value="INVOKER" onclick="action_fun.select(this)" class="radio_class_2" style="width: 80px;height: 29px;"/>' + '</span>'
                },
                {
                    xtype: 'panel',
                    width: 90,
                    html: '<span style="margin-right: 13px;">' + '<input name="v_saveSecurityField" type="button" value="DEFINER" onclick="action_fun.select(this)" class="radio_class_2" style="width: 80px;height: 29px;"/>' + '</span>'
                }]
            },
            {
                //决定性
                height: 55,
                layout: {
                    type: 'hbox',
                    align: 'top' //向上对其
                },
                items: [{
                    xtype: 'panel',
                    width: 130,
                    html: '<span style="margin-right: 13px;float: right;margin-top: 10px;font-weight: bold">' + '<span style="font-size: 13px;">决定性：</span>' + '</span>'
                },
                {
                    xtype: 'panel',
                    width: 120,
                    html: '<span style="margin-right: 13px;">' + '<input name="v_deterministicField" type="button" value="DETERMINISTIC" onclick="action_fun.select(this)" class="radio_class_1" style="width: 110px;height: 29px;"/>' + '</span>'
                },
                {
                    xtype: 'panel',
                    width: 140,
                    html: '<span style="margin-right: 13px;">' + '<input name="v_deterministicField" type="button" value="NOT DETERMINISTIC" onclick="action_fun.select(this)" class="radio_class_2" style="width: 130px;height: 29px;"/>' + '</span>'
                }]
            },
            {
                //数据访问
                height: 55,
                layout: {
                    type: 'hbox',
                    align: 'top' //向上对其
                },
                items: [{
                    width: 130,
                    xtype: 'panel',
                    html: '<span style="margin-right: 13px;float: right;margin-top: 10px;">' + '<span style="font-size: 13px;font-weight: bold">数据访问：</span>' + '</span>'
                },
                {
                    xtype: 'panel',
                    width: 90,
                    html: '<span style="margin-right: 12px;">' + '<input name="v_callMethodField" type="button" value="默认" onclick="action_fun.select(this)" class="radio_class_1" style="width: 80px;height: 29px;"/>' + '</span>'
                },
                {
                    xtype: 'panel',
                    width: 115,
                    html: '<span style="margin-right: 12px;">' + '<input name="v_callMethodField" type="button" value="CONTAINS SQL" onclick="action_fun.select(this)" class="radio_class_2" style="width: 105px;height: 29px;"/>' + '</span>'
                },
                {
                    xtype: 'panel',
                    width: 80,
                    html: '<span style="margin-right: 12px;">' + '<input name="v_callMethodField" type="button" value="NO SQL" onclick="action_fun.select(this)" class="radio_class_2" style="width: 70px;height: 29px;"/>' + '</span>'
                },
                {
                    xtype: 'panel',
                    width: 130,
                    html: '<span style="margin-right: 12px;">' + '<input name="v_callMethodField" type="button" value="READS SQL DATA" onclick="action_fun.select(this)" class="radio_class_2" style="width: 120px;height: 29px;"/>' + '</span>'
                },
                {
                    xtype: 'panel',
                    width: 140,
                    html: '<span style="margin-right: 12px;">' + '<input name="v_callMethodField" type="button" value="MODIFIES SQL DATA" onclick="action_fun.select(this)" class="radio_class_2" style="width: 130px;height: 29px;"/>' + '</span>'
                }]
            }

            ]
        });

        var win = new IDB.Window({
            width: 720,
            height: 260,
            title: '函数的选项设置',
            layout: 'fit',
            buttonAlign: 'center',
            closable: true,
            items: [baseInfoForm],
            buttons: [{
                text: '确 定',
                handler: function() {
                    var data = {
                        sqlSecurity: action_fun.getValueByName("v_saveSecurityField"),
                        deterministic: action_fun.getValueByName("v_deterministicField"),
                        dataCallMethod: action_fun.getValueByName("v_callMethodField"),
                        script: Ext.getCmp('sql_content').getValue()
                    };
                    ajax({
                        url: '/structure/function/set-function-config.do',
                        params: data,
                        success: function(resp) {
                            var json = jsonDecode(resp.responseText);
                            if (json.success) {
                                setContent(json.root);
                                win.close();
                            } else {
                                $.message.error(json.root);
                            }
                        }
                    });
                }
            },
            {
                text: '关 闭',
                handler: function() {
                    win.close();
                }
            },
            {
                text: '帮助',
                handler: function() {
                    action_fun.linkHelp();
                }
            }]
        });

        if (config['sqlSecurity']) {
            action_fun.selectByValue("v_saveSecurityField", config['sqlSecurity']);
        }
        if (config['dataCallMethod']) {
            action_fun.selectByValue("v_callMethodField", config['dataCallMethod']);
        }
        if (config['deterministic']) {
            action_fun.selectByValue("v_deterministicField", config['deterministic']);
        }
    },
    select: function(obj) {
        var name = obj.name;
        var fields = document.getElementsByName(name);
        for (var i = 0,
        size = fields.length; i < size; i++) {
            if (fields[i] == obj) {
                fields[i].setAttribute("class", "radio_class_1");
            } else {
                fields[i].setAttribute("class", "radio_class_2");
            }
        }
    },
    selectByValue: function(name, value) {
        var fields = document.getElementsByName(name);
        for (var i = 0,
        size = fields.length; i < size; i++) {
            if (fields[i].value == value.toUpperCase()) {
                fields[i].setAttribute("class", "radio_class_1");
            } else {
                fields[i].setAttribute("class", "radio_class_2");
            }
        }
    },
    getValueByName: function(name) {
        var fields = document.getElementsByName(name);
        var node = null;
        for (var i = 0,
        size = fields.length; i < size; i++) {
            if (fields[i].getAttribute("class") == "radio_class_1") {
                node = fields[i];
                break;
            }
        }
        if (node && node.value != "默认") {
            return node.value;
        }
    }
};

var getHeaderPanel = function() {
    return new Ext.Panel({
        id: 'header_panel_panel',
        region: 'north',
        height: 55,
        bodyStyle: 'border-style:solid;border-width:1px;border-color:#eee;',
        border: true,
        html: '<div id="header_panel_div" style="height: 100%">&nbsp;</div>'
    });
};

var getMsgPanel = function() {
    return new Ext.Panel({
        id: 'msg_panel',
        region: 'south',
        height: 100,
        hidden: true,
        split: true,
        autoScroll: true,
        html: '<div style="font-size: 13px" id="msg_panel_content">&nbsp;</div>'
    });
};

var getContentPanel = function() {
    var sqlArea = new Ext.ux.form.field.CodeMirror({
        value: '',
        id: 'sql_content',
        autoScroll: true,
        styleActiveLine: true
    });
    
    return new Ext.Panel({
        layout: 'fit',
        region: 'center',
        bodyStyle: 'border-style:solid;border-width:1px;border-color:#eee;',
        border: true,
        items: [sqlArea]
    });
};

var initHeaderPanel = function() {
    Ext.getCmp('main_panel').add(getHeaderPanel());
    var subStr = "";
    if(envType!='PRD'){
    	subStr += '';
    }
    document.getElementById('header_panel_div').style.backgroundColor = "#f5f5f5";
    document.getElementById('header_panel_div').innerHTML = '<input type="button" value="保存" onclick="action_fun.saveFunction(\'false\');" class="button_class_1" style="width: 80px;height: 32px;margin: 10px 0 0 10px;"/>' + 
    '<span style="width: 80px;height: 32px;margin: 10px 0 0 10px;"/>当前库：<span id="db_name_div">' + nowDBName + "</span></span>" + '<input type="button" value="帮助" onclick="action_fun.linkHelp();" class="button_class_2" style="width: 90px;height: 32px;float: right;margin: 10px 30px 0 0;"/>';
};

var resetNowDBName = function() {
    document.getElementById('db_name_div').innerHTML = nowDBName;
};

var setContent = function(v) {
    var sqlContent = Ext.getCmp('sql_content');
    sqlContent.setValue(v);
    sqlContent.editor.focus(true);
    var index = v.toUpperCase().indexOf("BEGIN");
    var tmp = v.substring(0, index);
    var rows = tmp.length - tmp.replaceAll("\n", "").length;
    var rowContent = sqlContent.editor.getLine(rows + 1);
    sqlContent.editor.setCursor(rows + 1, rowContent.length);
};

var initAll = function() {
    if (v_functionName) {
        initHeaderPanel();
        setContent(v_functionContent);
        if (v_init_option == 'execute') {
            action_fun.executeFunction();
        }
    } else {
        showNewFunctionBaseInfo();
    }
};

var func_name,
	func_auserEmail,
	func_projectName,
	func_returnType,
	func_sqlUsage,
	func_comment;
var showNewFunctionBaseInfo = function() {
	var dbcolumnTypeArray;
	if(now_db_type == 'oracle'){
		dbcolumnTypeArray = oracleColumnTypeArray;
	}else{
		dbcolumnTypeArray = columnTypeArray;
	}
    var columnTypeStore = new Ext.data.Store({
        fields:['data' , 'label'],
        data:dbcolumnTypeArray
    });
    var projectStore = new Ext.data.Store({
		fields:['data','label'],
		data : projectListArray
	});
    var baseFuncInfoForm = new IDB.FormPanel({
        region: 'center',
        layout: 'column',
        defaults: {
            margin: '5 2 2 0',
            width: 500,
            columnWidth: 1,
            labelWidth: 90,
            allowBlank: false
        },
        items: [{
            fieldLabel: '函数名称',
            blankText: '函数名称不能为空',
            xtype: 'textfield',
            name: 'name',
            maxLength: 128,
            maxLengthText: '函数名称请小于128个字符'
        },{
        	fieldLabel:'<span style="color:red">*</span>邮箱',
     	   	emptyText:'请输入部门负责人邮箱地址',
     	   	allowBlank:false,
     	   	name:'auserEmail',
     	   	blankText:'部门负责人邮箱地址不能为空'
        },{
        	fieldLabel:'项目组',
        	xtype:'combo',
        	triggerAction:'all',
        	displayField:'label',
        	valueField:'data',
        	queryMode:'local',
        	name:'projectName',
        	forceSelection:true,
        	typeAhead:true,
        	editable:false,
        	store:projectStore
        },{
            fieldLabel: '返回值类型',
            blankText: '返回值类型不能为空',
            xtype: 'combo',
            name: 'returnType',
            triggerAction: 'all',
            displayField: 'label',
            valueField: 'data',
            queryMode: 'local',
            typeAhead: true,
            store: columnTypeStore
        },{
        	padding:'5 0 0 0',
        	fieldLabel:'<span style="color:red">*</span> SQL用途',
        	allowBlank:false,
        	name:'sqlUsage',
        	blankText:'SQL用途说明不能为空.'
        },{
            fieldLabel: '描述',
            xtype: 'textarea',
            height: 80,
            maxLength: 1024,
            maxLengthText: '描述的内容请不要超过1024个字符',
            name: 'comment',
            allowBlank: true
        }]
    });

    var toRows;
    var win = new IDB.Window({
        width: 520,
        height: 260,
        title: '请填写新增函数的基本信息',
        layout: 'fit',
        closable: false,
        buttonAlign: 'center',
        items: [baseFuncInfoForm],
        buttons: [{
            text: '确 定',
            handler: function() {
                if (baseFuncInfoForm.isValid()) {
                    initHeaderPanel();
                    var sqlContent = Ext.getCmp('sql_content');
                    sqlContent.setValue(getCreateFunctionSQL());
                    sqlContent.editor.focus(true);
                    sqlContent.editor.setCursor(toRows, 2);
                    win.close();
                }
            }
        },{
        	text:'取 消',
        	handler:function(){
        		win.close();
        	}
        }],
        listeners: {
            'afterrender': function() {
                setTimeout(function() {
                	baseFuncInfoForm.getForm().findField('name').focus(true);
                },
                200);
            }
        }
    });
    
    var getCreateFunctionSQL = function() {
        toRows = 5;
        var values = baseFuncInfoForm.getValues();
        func_name = values['name'],
    	func_auserEmail = values['auserEmail'],
    	func_projectName = values['projectName'],
    	func_returnType = values['returnType'],
    	func_sqlUsage = values['sqlUsage'],
    	func_comment = values['comment'];
        var content = "CREATE FUNCTION " + nowDBName.replaceAll('`', '') + "." + values['name'].trim().replaceAll('`', '') + "()\n";
        content += '\tRETURNS ' + values['returnType'] + "\n";
        content += "\tDETERMINISTIC\n";
        var comment = values['comment'];
        if (comment && comment.trim()) {
            comment = comment.trim();
            toRows += comment.length - comment.replaceAll("\n", "").length + 1;
            content += '\tCOMMENT \'' + comment.replaceAll("'", "''") + "'\n";
        }
        content += '\nBEGIN\n\t\n';
        content += '\tRETURN <value>;\n';
        content += 'END\n';
        return content;
    };
};
